package com.region.loadbalancer.monitor.stat;

import com.region.loadbalancer.group.Server;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http protocol detection service
 *
 * @author liujieyu
 * @date 2023/5/26 13:44
 * @desciption
 */
public class HttpDetectionConnection implements DetectionConnection {

    /**
     * The default timeout is 100 milliseconds
     */
    private int timeout = 100;

    public HttpDetectionConnection() {
        this(100);
    }

    public HttpDetectionConnection(int timeout) {
        this.timeout = timeout;
    }

    @Override
    public boolean connect(Server server) {
        try {
            URL url = new URL(server.getServerAllInfo());
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(this.timeout);
            int responseCode = urlConnection.getResponseCode();
            urlConnection.disconnect();
            if (responseCode < 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
